#include "../include/common.h"




int init_thread_pool(threadpool_t* pool,int worknum)
{
    init_tidarr(&pool->thread_arr,worknum);
    init_taskqueue(&pool->queue);

    pthread_mutex_init(&pool->mutex,NULL);
    pthread_cond_init(&pool->cond,NULL);
    pool->exitFlag = 0; // 初始化退出标志位为0  
    pool->logfd = open("../log/log.txt", O_CREAT | O_APPEND | O_RDWR, 0666);
    return 0;
}


int exitPipe[2];//只有全局变量才能被signal的handler访问
void handler(int signum){
    printf("signum = %d\n", signum);
    write(exitPipe[1],"1",1);
}


int main()
{
    
    // pipe(exitPipe); //埋一根管道
    // if(fork()){
    //     //父进程 写管道
    //     close(exitPipe[0]);
    //     signal(SIGUSR1,handler);
    //     wait(NULL); // 父进程一般处于等待
    //     printf("Parent is going to exit!\n");
    //     exit(0);
    // }

    //1.初始化线程池结构体
    threadpool_t threadpool;
    init_thread_pool(&threadpool, 4);

    //2.创建线程池
    creat_worker(&threadpool);


    //3.进行tcp连接

    char* ip="192.168.7.22";
    char *port="36666";

    int socketfd = creat_tcp(ip, port);

    int epfd=epoll_create(1);
    epoll_add_event(epfd,socketfd);
    epoll_add_event(epfd, exitPipe[0]); // 添加管道读端到epoll

    struct epoll_event readyevent[1024];
    
    int readyset=epoll_wait(epfd,readyevent,1024,-1);

    //处理就绪事件
    while(1)
    {
        for(int i=0;i<readyset;i++)
        {
            
            if(readyevent[i].data.fd==socketfd)
            {
                
                int netfd=accept(socketfd,NULL,NULL);
                PRINT_LOG_FILE(threadpool.logfd,"new client", 0, "success","new client accepted",threadpool.mutex);
                printf("new client connected;netfd= %d\n", netfd);
                pthread_mutex_lock(&threadpool.mutex);
                en_queue(&threadpool.queue,netfd);
                pthread_cond_broadcast(&threadpool.cond);
                pthread_mutex_unlock(&threadpool.mutex);
            }
            else {
                
            
            }
        }    
        
    }


}
